package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.config.AppMinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Slf4j
@Service
public class FileUploadServiceImpl  implements FileUploadService {



    @Autowired
    MinioClient minioClient;

    @Autowired
    AppMinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        //文件上传功能 http://192.168.200.200:9000/gmall/%E5%8D%A0%E6%81%92%E9%80%9A.jpg
        String url = minioProperties.getEndpoint() + minioProperties.getBucket() + "/";
        try {
            //文件流
            InputStream inputStream = file.getInputStream();
            //文件名
            String filename = UUID.randomUUID().toString().replace("-","")+"_"+file.getOriginalFilename();
            url += filename;
            //前端提交来的文件的内容类型
            String contentType = file.getContentType();

            PutObjectOptions options = new PutObjectOptions(-1,5 * 1024 * 1024);
            options.setContentType(contentType);

            minioClient.putObject(
                    minioProperties.getBucket(),
                    filename,
                    inputStream,
                    options
                    );

            log.info("文件上传成功：【{}】",filename);


        } catch (Exception e) {
            log.error("文件上传出错：msg：{}",e.getStackTrace());
        }

        return url;
    }
}
